package org.nox.helloseries.server.connector.html.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;
import org.nox.helloseries.server.connector.html.XPathSearcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultXPathSearcher implements XPathSearcher
{
    private static Logger LOG = LoggerFactory.getLogger( XPathSearcher.class );

    private static final String XPATH_TITLE = "//title";

    private HtmlCleaner cleaner = null;

    public DefaultXPathSearcher()
    {
        // TODO Auto-generated constructor stub
    }

    @Override
    public String getAttributeFromXpath( HttpEntity httpEntity, String xpath, String attributeName )
    {
        try
        {
            InputStream input = httpEntity.getContent();

            if ( input != null )
            {
                try
                {
                    TagNode root = getHtmlCleaner().clean( new InputStreamReader( input ) );

                    // Récupération du title
                    Object[] nodesObjects = root.evaluateXPath( XPATH_TITLE );
                    if ( nodesObjects.length > 0 )
                    {
                        TagNode node = (TagNode) nodesObjects[0];
                        LOG.info( "Recherche sur le document HTML : {}", node.getText() );
                    }

                    nodesObjects = root.evaluateXPath( xpath );

                    if ( nodesObjects.length > 0 )
                    {

                        TagNode node = (TagNode) nodesObjects[0];
                        return node.getAttributeByName( attributeName );
                    }
                }

                catch ( XPatherException e )
                {
                    LOG.error( "XPatherException", e );
                }
            }
        }
        catch ( IOException e )
        {
            LOG.error( "IOException", e );
        }
        return null;
    }

    private HtmlCleaner getHtmlCleaner()
    {
        if ( cleaner == null )
        {
            cleaner = new HtmlCleaner();
            CleanerProperties props = cleaner.getProperties();
            props.setAllowHtmlInsideAttributes( true );
            props.setAllowMultiWordAttributes( true );
            props.setRecognizeUnicodeChars( true );
            props.setOmitComments( true );
        }
        return cleaner;
    }
}
